package com.xspace.android.xafcommon.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.xspace.android.imcommon.utils.AppUtil;
import com.xspace.android.xafcommon.appliction.BaseApplication;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppUtils {
    public final static String isNotifyAlert = "isNotifyAlert";
    public final static String isNotifyOpen = "isNotifyOpen";
    public final static String IM_IOC = "IM_IOC";
    public final static String isNotifyvibation = "isNotifyvibation";
    public final static String url = "url";
    public final static String userName = "userName";
    public final static String password = "password";
    public final static String host = "host";
    public final static String port = "port";

    public static boolean isRunningForeground(Context context, String[] topActivity) {
        try {
            String packageName = getPackageName(context);
            String topActivityClassName = getTopActivityName(context);
            if (packageName != null && topActivityClassName != null) {
                for (int i = 0; i < topActivity.length; i++) {
                    if (topActivity[i].startsWith(packageName)) {
                        return true;
                    }
                }
                return false;
            } else {
                System.out.println("---> isRunningBackGround");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager = (ActivityManager) (context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    public static String getPackageName(Context context) {
        String packageName = context.getPackageName();
        return packageName;
    }

    /**
     * 已处理音频地址
     */
    public static final String VOICE_ADDRESS = android.os.Environment.getExternalStorageDirectory() + "/ctnq/voice/";





    /**
     * @param @param  context
     * @param @return
     * @return
     * @throws
     * @Description: 过去程序版本号
     */
    public static int getVersion(Context context) {
        PackageManager packageManager = context.getPackageManager();
        int code;
        try {
            code = packageManager.getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            code = 1;
        }
        return code;
    }

    /**
     * @param @param  context
     * @param @return
     * @return
     * @throws
     * @Description: 过去程序版本名称
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        String code = "";
        try {
            code = packageManager.getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            code = "";
        }
        return code;
    }



    /**
     * inputStream 转 String
     *
     * @param inStream
     * @param encode
     * @return
     */
    public static String inputStreamToString(InputStream inStream, String encode) {
        byte[] data = readStream(inStream);
        String str = null;
        if (data != null) {
            try {
                str = new String(data, encode);
            } catch (UnsupportedEncodingException e) {
                str = null;
            }
        }
        return str;

    }



    /**
     * 创建文件夹
     *
     * @param dir
     */
    public static void createDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * check if sdcard exist
     *
     * @return
     */
    public static boolean isSdcardExist() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 放缩到指定大小
     *
     * @param context
     * @param imagePath
     * @param width
     * @param height
     * @throws Exception
     */
    public static void scalePictureGivenSize(Activity context,
                                             String imagePath, int width, int height) throws Exception {
        byte[] photoBytes = scalePicture(context, width, height,
                readStream(new FileInputStream(imagePath)));
        FileOutputStream fos = new FileOutputStream(imagePath);
        fos.write(photoBytes);
        fos.close();
        photoBytes = null;
    }


    /**
     * 获取md5加密
     *
     * @param s       要加密的字符串
     * @param isUpper 是否大小写
     * @return
     */
    public final static String MD5(String s, boolean isUpper) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            String md5Str = new String(str);
            if (!isUpper) {
                md5Str = md5Str.toLowerCase();
            } else {
                md5Str = md5Str.toUpperCase();
            }
            return md5Str;
        } catch (Exception e) {
            return null;
        }
    }

    public static DisplayMetrics getScreenWidthAndHeight(Activity mContext) {
        DisplayMetrics metric = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric;
//        int width = metric.widthPixels; // 屏幕宽度（像素）
//        int height = metric.heightPixels; // 屏幕高度（像素）
//        LogUtil.d("screen width=>" + width + ",height=>" + height);
    }


    /**
     * 获取手机显示数据.
     *
     * @param activity 活动对象
     * @return 手机手机显示数据
     */
    public static DisplayMetrics getDisplayMetrics(Activity activity) {
        if (activity != null) {
            DisplayMetrics metric = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
            return metric;
        } else {
            throw new RuntimeException("Activity must not be null.");
        }
    }

    public static float dpToPixel(Activity activity, float dp) {
        return dp * (getDisplayMetrics(activity).densityDpi / 160F);
    }

    /**
     * 手机号码去杂
     *
     * @param phoneNum
     * @return
     */
    public static String getParseredPhoneNum(String phoneNum) {
        if (phoneNum == null) {
            return null;
        }
        String tempPhoneNum = phoneNum;
        if (tempPhoneNum.startsWith("+86")) {
            tempPhoneNum = tempPhoneNum.substring(3);
        } else if (tempPhoneNum.startsWith("86")) {
            tempPhoneNum = tempPhoneNum.substring(2);
        }
        // 过滤非数字的任何东西
        int size = tempPhoneNum.length();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; i++) {
            if (!(TextUtils.isEmpty(String.valueOf(tempPhoneNum.charAt(i)).trim())
                    || !Character.isDigit(tempPhoneNum.charAt(i)))) {
                sb.append(tempPhoneNum.charAt(i));
            }
        }
        return sb.toString();
    }

    public static void download(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 验证手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean ValidatePhone(String mobile) {
        if (mobile == null) {
            return false;
        }
        Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 验证数字
     *
     * @param str
     * @return
     */
    public static boolean ValidateNumber(String str) {
        if (str == null) {
            return false;
        }
        Pattern p = Pattern.compile("^\\d+$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 音频播放
     *
     * @param str
     * @return
     */
    static MediaPlayer mMediaPlayer;

    public static void playMusic(String name) {
        mMediaPlayer = new MediaPlayer();

        try {

            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
            }
            mMediaPlayer.reset();
            File file = new File(name);
            FileInputStream fis = new FileInputStream(file);
            mMediaPlayer.setDataSource(fis.getFD());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    if (mMediaPlayer != null) {
                        mMediaPlayer.stop();
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                    }
                }
            });
            if (fis != null) {
                fis.close();
                fis = null;
            }

        } catch (Exception e) {
            // VolleyLog.wtf("ImagePgView", e, "playMusic error==>%s",
        }
    }

    /**
     * long类型时间转换为yyyy-MM-dd HH:mm:ss格式时间
     *
     * @param time
     * @return
     */
    public static String formatTime(String format, String time) {
        format = (format == null || format.length() <= 0) ? "yyyy-MM-dd HH:mm:ss" : format;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {

            return sdf.format(new Date(Long.parseLong(time)));
        } catch (Exception e) {
            return sdf.format(new Date(System.currentTimeMillis()));

        }
    }

    // date类型转换为String类型
    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    // string类型转换为date类型
    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String formatType, String strTime) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    public static String StringToString(String format, String time) {
        format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return dateToString(stringToDate("yyyyMMddHHmmss", time), format);
        } catch (Exception e) {
            return sdf.format(new Date(System.currentTimeMillis()));
        }
    }

    /**
     * 获取当前时间
     *
     * @param formater , 为空，则采用默认格式：yyyyMMddHHmmss
     * @return
     */
    public static String getCurrentTime(String formater) {
        String defaultFormater = (formater == null || formater.trim().length() <= 0) ? "yyyyMMddHHmmss" : formater;
        SimpleDateFormat sdf = new SimpleDateFormat(defaultFormater);
        return sdf.format(new Date(System.currentTimeMillis()));
    }

    public static long dateToLong(Date date) {
        return date.getTime();
    }

    public static String getCurrentTime() {
        String defaultFormater = "yyyyMMddHHmmss";
        SimpleDateFormat sdf = new SimpleDateFormat(defaultFormater);
        return sdf.format(new Date(System.currentTimeMillis()));
    }

    private static long day = 1000 * 60 * 60 * 24;
    private static long hour = 1000 * 60 * 60;
    private static long minutes = 1000 * 60;

    public static String timeLater(String disTime) {
        String value = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date d = new Date();
            Date date = sdf.parse(disTime);
            long times = d.getTime() - date.getTime();
            if (times / day > 0) {
                if ((times / day) >= 14) {
                    return "2周前";
                } else {
                    return (times / day) + "天前";
                }
            } else if (times / hour > 0) {
                return (times / hour) + "小时前";
            } else {
                return (times / minutes) + "分钟前";
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取当前时间
     *
     * @param formater , 为空，则采用默认格式：yyyyMMddHHmmss
     * @return
     */
    public static String getWebTime(String formater, int length) {
        String time = "";
        if (length == 8) {
            time = formater.substring(0, 4) + "-" + formater.substring(4, 6) + "-" + formater.substring(6, 8);
        }
        if (length == 12) {
            time = formater.substring(0, 4) + "-" + formater.substring(4, 6) + "-" + formater.substring(6, 8) + "\t"
                    + formater.substring(8, 10) + ":" + formater.substring(10, 12);
        }
        return time;
    }

    /**
     * 生成照片名称
     *
     * @return
     */
    public static String generateImageName() {
        return getCurrentTime(null) + AppConstant.SUFFIX_IMAGE;
    }

    /**
     * 生成音频名称
     *
     * @return
     */
    public static String generateVoiceName() {
        return getCurrentTime(null) + AppConstant.SUFFIX_VOICE;
    }

    /**
     * 输入流转换为string
     *
     * @param is
     * @return
     * @throws Exception
     */
    public static String parser(InputStream is) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(is));
        StringBuffer testDataResp = new StringBuffer();
        for (String s = bf.readLine(); s != null; s = bf.readLine()) {
            testDataResp.append(s);
        }
        try {
            is.close();
        } catch (Exception e) {
        }
        return testDataResp.toString();
    }

    /**
     * 获取派讯alpha
     *
     * @param str
     * @return
     */
    public static String getAlpha(String str) {

        if (str == null) {
            return "#";
        }
        if (str.trim().length() == 0) {
//			LogUtils.d("getAlpha===" + str);
            str = str.trim();
            return "#";
        }
        char c = str.substring(0, 1).charAt(0);
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase();
        } else {
            String fs = getFirstSpell(str);
            if (TextUtils.isEmpty(fs))
                return "#";
            c = fs.substring(0, 1).charAt(0);

            if (pattern.matcher(c + "").matches()) {
                return (c + "").toUpperCase();
            } else {

                return "#";
            }
        }
    }

    /**
     * 汉字转换为汉语拼音首字母 花花大神->hhds
     *
     * @param chines 汉字
     * @return 拼音
     */
    public static String getFirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char curchar : arr) {
            if (curchar > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(curchar);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    public static void organizeAndStart(Activity activity, Class<?> classes, Map<String, String> paramMap) {
        Intent intent = new Intent(activity, classes);
        if (null != paramMap) {
            Set<String> set = paramMap.keySet();
            for (Iterator<String> iterator = set.iterator(); iterator.hasNext(); ) {
                String key = iterator.next();
                intent.putExtra(key, paramMap.get(key));
            }
        }
        activity.startActivityForResult(intent, Activity.RESULT_FIRST_USER);
    }

    public static boolean isConnected(Context ctx) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnected();
    }

    // 发送停止服务广播
    public static void sendStopServiceBroadcast(Context ctx) {
        Intent intent = new Intent(AppConstant.BR_SERVICE_HANDLE);
        intent.putExtra(AppConstant.BR_KEY_CMD, AppConstant.BR_SERVICE_HANDLE_VALUE_STOP);
        ctx.sendBroadcast(intent);
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static Bitmap getSmallLocalBitmap(Activity context, String url) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;

        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(url);
            int fileLen = fis.available();
            if (fileLen > 100 * 1024) {
                options.inSampleSize = 8; // width，hight设为原来的十分一
            }
            bitmap = BitmapFactory.decodeStream(fis, null, options);
            int degree = readPictureDegree(url);
            System.out.println("--------------------:" + degree);
            if (degree > 0) {
                bitmap = adjustPhotoRotation(bitmap, degree);
            }
            if (fis != null) {
                fis.close();
                fis = null;

            }
        } catch (Exception e) {
            bitmap = null;
        }
        return bitmap;
    }

    /**
     * 填充字符串
     *
     * @param str
     * @param n
     * @param isLeft true左填充,false 右填充
     * @param c      填充字符串
     * @return
     */
    public static String change(String str, int n, boolean isLeft, String c) {
        c = (c == null) ? "0" : c;
        if (str == null || str.length() >= n)
            return str;
        String s = "";
        for (int i = str.length(); i < n; i++)
            s += c;
        if (isLeft)
            return s + str;
        else
            return str + s;
    }

    private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
        if (bitmap == null)
            return null;

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        // Setting post rotate to 90
        Matrix mtx = new Matrix();
        mtx.postRotate(rotate);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

    public static Bitmap getFile(String fileName) {
        Bitmap bm = null;
        BufferedOutputStream bos = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            bm = BitmapFactory.decodeFile(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    private static Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
        try {
            Matrix m = new Matrix();
            m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
            float targetX, targetY;
            if (orientationDegree == 90) {
                targetX = bm.getHeight();
                targetY = 0;
            } else {
                targetX = bm.getHeight();
                targetY = bm.getWidth();
            }

            final float[] values = new float[9];
            m.getValues(values);

            float x1 = values[Matrix.MTRANS_X];
            float y1 = values[Matrix.MTRANS_Y];

            m.postTranslate(targetX - x1, targetY - y1);

            Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);

            Paint paint = new Paint();
            Canvas canvas = new Canvas(bm1);
            canvas.drawBitmap(bm, m, paint);
            return bm1;
        } catch (Exception e) {
            return bm;
        }

    }

    private static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static Bitmap getLocalBitmap(Activity context, String url) throws IOException {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        BitmapFactory.decodeFile(url, options);

        // Calculate inSampleSize
        options.inSampleSize = 8;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(url, options);

        // FileInputStream fis = new FileInputStream(url);
        // Bitmap bitmap = BitmapFactory.decodeStream(fis);
        int degree = readPictureDegree(url);
        if (degree > 0) {
            bitmap = adjustPhotoRotation(bitmap, degree);
        }
        // if (fis != null) {
        // fis.close();
        // fis = null;
        // }
        return bitmap;
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static int[] getImageSize(String url) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(url, options);
        /* 这里返回的bmp是null */
        return new int[]{options.outWidth, options.outHeight};
    }

//    /**
//     * 保存图片
//     *
//     * @param bitmap
//     * @param filePath
//     * @throws Exception
//     */
//    public static void storeInSD(InputStream is, String filePath) throws Exception {
//        createDirs();
//
//        byte[] photoBytes = AppUtil.readStream(is);
//        FileOutputStream fos = new FileOutputStream(filePath);
//        fos.write(photoBytes);
//        fos.flush();
//        fos.close();
//    }

//    public static void createDirs() {
//        // File file = new File(AppConstant.IMAGE_ADDRESS_UN);
//        // if (!file.exists()) {
//        // file.mkdirs();
//        // }
//        File file = new File(AppConstant.IMAGE_ADDRESS);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        file = new File(AppConstant.IMAGE_HEAD);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        file = new File(AppConstant.VOICE_ADDRESS);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        // file = new File(AppConstant.VOICE_ADDRESS_UN);
//        // if (!file.exists()) {
//        // file.mkdirs();
//        // }
//        file = new File(AppConstant.VOICE_ADDRESS_DL);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        file = new File(AppConstant.IMAGE_ADDRESS_DL);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//    }

    /**
     * 压缩图片，不改变大小
     *
     * @param context
     * @param imagePath
     * @throws Exception
     */
    public static void scalePictureKeepOrginSize(Activity context, String imagePath) throws Exception {
        int[] imageSize = AppUtil.getImageSize(imagePath);
        scalePictureGivenSize(context, imagePath, imageSize[0], imageSize[1]);
    }

    /**
     * 主要用于工作日志压缩
     *
     * @param context
     * @param imagePath
     * @throws Exception
     */
    public static void scalePictureKeepOrginSizeForLog(Activity context, String imagePath) throws Exception {
        int[] imageSize = AppUtil.getImageSize(imagePath);
        byte[] photoBytes = scalePictureSmall(context, imageSize[0], imageSize[1],
                AppUtil.readStream(new FileInputStream(imagePath)));
        Log.v("apputil", "scalePictureKeepOrginSizeForLog photoBytes:" + photoBytes.length + " ");
        File f = new File(imagePath);
        if (f.exists() && f.isFile())
            f.delete();
        FileOutputStream fos = new FileOutputStream(imagePath);
        fos.write(photoBytes);
        fos.close();
        photoBytes = null;

    }



    /**
     * 缩放图片
     *
     * @param context
     * @param maxWidth
     * @param maxHeight
     * @param photoByte
     * @return
     * @throws Exception
     */
    public static byte[] scalePicture(Activity context, int maxWidth, int maxHeight, byte[] photoByte)
            throws Exception {
        int windowWidth = context.getWindowManager().getDefaultDisplay().getWidth();
        int windowHeight = context.getWindowManager().getDefaultDisplay().getHeight();
        maxWidth = (maxWidth <= 0) ? windowWidth : maxWidth;
        maxHeight = (maxHeight <= 0) ? windowHeight : maxHeight;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ByteArrayInputStream isBm = new ByteArrayInputStream(photoByte);
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        newOpts.outWidth = maxWidth;
        newOpts.outHeight = maxHeight;
        newOpts.inTempStorage = new byte[1024 * 1024 * 3];
        Bitmap photo = BitmapFactory.decodeStream(isBm, null, newOpts);
        int srcWidth = newOpts.outWidth;
        int srcHeight = newOpts.outHeight;
        int desWidth = 0;
        int desHeight = 0;
        double ratio = 0.0;
        if (srcWidth > srcHeight) {
            ratio = srcWidth / maxWidth;
            desWidth = maxWidth;
            desHeight = (int) (srcHeight / ratio);
        } else {
            ratio = srcHeight / maxHeight;
            desHeight = maxHeight;
            desWidth = (int) (srcWidth / ratio);
        }
        newOpts.inSampleSize = (int) (ratio) + 1;
        if (ratio == 1) {
            if (photoByte.length <= 100 * 1024 || desHeight < 1024) {
                newOpts.inSampleSize = 1;
            }
        }
        //Log.v("apputil", "photoByte:"+photoByte.length+" ratio:"+ratio);
        //Log.v("apputil", "desHeight:"+desHeight+" desWidth:"+desWidth+" newOpts.inSampleSize:"+newOpts.inSampleSize);
        newOpts.inJustDecodeBounds = false;
        newOpts.outWidth = desWidth;
        newOpts.outHeight = desHeight;
        isBm = new ByteArrayInputStream(photoByte);
        photo = BitmapFactory.decodeStream(isBm, null, newOpts);
        if (photoByte.length <= 100 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d<= 100k", photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        } else if (photoByte.length > 100 * 1024 && photoByte.length <= 500 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d> 100k && fileLen <= 500k",
            // photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
        } else if (photoByte.length > 500 * 1024 && photoByte.length <= 1024 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d> 500k && fileLen <= 1m",
            // photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
        } else {
            // VolleyLog.d("AppUtil", "图片大小%d>1m", photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 20, stream);
        }
        photoByte = stream.toByteArray();
        newOpts.inTempStorage = new byte[0];
        stream.close();
        isBm.close();
        photo.recycle();
        photo = null;
        return photoByte;
    }

    public static byte[] scalePictureSmall(Activity context, int maxWidth, int maxHeight, byte[] photoByte)
            throws Exception {
        int windowWidth = context.getWindowManager().getDefaultDisplay().getWidth();
        int windowHeight = context.getWindowManager().getDefaultDisplay().getHeight();
        maxWidth = (maxWidth <= 0) ? windowWidth : maxWidth;
        maxHeight = (maxHeight <= 0) ? windowHeight : maxHeight;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ByteArrayInputStream isBm = new ByteArrayInputStream(photoByte);
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        newOpts.outWidth = maxWidth;
        newOpts.outHeight = maxHeight;
        newOpts.inTempStorage = new byte[1024 * 1024 * 3];
        Bitmap photo = BitmapFactory.decodeStream(isBm, null, newOpts);
        int srcWidth = newOpts.outWidth;
        int srcHeight = newOpts.outHeight;
        int desWidth = 0;
        int desHeight = 0;
        double ratio = 0.0;
        if (srcWidth > srcHeight) {
            ratio = srcWidth / maxWidth;
            desWidth = maxWidth;
            desHeight = (int) (srcHeight / ratio);
        } else {
            ratio = srcHeight / maxHeight;
            desHeight = maxHeight;
            desWidth = (int) (srcWidth / ratio);
        }
        newOpts.inSampleSize = (int) (ratio) + 3;
        if (ratio == 1) {
            if (photoByte.length <= 100 * 1024 || desHeight < 1024) {
                newOpts.inSampleSize = 1;
            }
        }
        Log.v("apputil", "scalePictureSmall photoByte:" + photoByte.length + " ratio:" + ratio);
        Log.v("apputil",
                "desHeight:" + desHeight + " desWidth:" + desWidth + " newOpts.inSampleSize:" + newOpts.inSampleSize);
        newOpts.inJustDecodeBounds = false;
        newOpts.outWidth = desWidth;
        newOpts.outHeight = desHeight;
        isBm = new ByteArrayInputStream(photoByte);
        photo = BitmapFactory.decodeStream(isBm, null, newOpts);
        if (photoByte.length <= 100 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d<= 100k", photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        } else if (photoByte.length > 100 * 1024 && photoByte.length <= 500 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d> 100k && fileLen <= 500k",
            // photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
        } else if (photoByte.length > 500 * 1024 && photoByte.length <= 1024 * 1024) {
            // VolleyLog.d("AppUtil", "图片大小:%d> 500k && fileLen <= 1m",
            // photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 20, stream);
        } else {
            // VolleyLog.d("AppUtil", "图片大小%d>1m", photoByte.length);
            photo.compress(Bitmap.CompressFormat.JPEG, 10, stream);
        }
        photoByte = stream.toByteArray();
        Log.v("apputil", "scalePictureSmall photoByte:" + photoByte.length + " end");
        newOpts.inTempStorage = new byte[0];
        stream.close();
        isBm.close();
        photo.recycle();
        photo = null;
        return photoByte;
    }

    public static byte[] readStream(InputStream inStream) {
        byte[] buffer = new byte[1024];
        int len = -1;
        byte[] data = null;
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            data = outStream.toByteArray();
            outStream.close();
            inStream.close();
        } catch (Exception e) {
        }
        return data;

    }

    /**
     * 移动文件
     *
     * @param srcFileName 源文件完整路径
     * @param destDirName 目的目录完整路径
     * @return 文件移动成功返回true，否则返回false
     */
    public synchronized static boolean moveFile(String srcFileName, String destDirName) {
        File srcFile = new File(srcFileName);
        if (!srcFile.exists() || !srcFile.isFile())
            return false;

        File destDir = new File(destDirName);
        if (!destDir.exists())
            destDir.mkdirs();
        return srcFile.renameTo(new File(destDirName + File.separator + srcFile.getName()));
    }

    public static int getOSVersion() {
        return Build.VERSION.SDK_INT;
    }

    public static void saveFile(Bitmap bm, String fileName) {
        BufferedOutputStream bos = null;
        try {
            File myCaptureFile = new File(fileName);
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        } catch (Exception e) {
            // VolleyLog.wtf("AppUtil", e, "saveFile error==>%s",
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void saveHandFile(Bitmap bm, String fileName) {
        BufferedOutputStream bos = null;
        try {
            File myCaptureFile = new File(fileName);
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        } catch (Exception e) {
            // VolleyLog.wtf("AppUtil", e, "saveFile error==>%s",
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public synchronized static boolean renameFile(String oldName, String newName) {
        try {
            File resFile = new File(oldName);
            File newFile = new File(newName);
            return resFile.renameTo(newFile);
        } catch (Exception e) {
            // VolleyLog.wtf("AppUtil", e, "saveFile error==>%s",
            return false;
        }
    }

    /**
     * 是否是自己系统的多媒体消息
     *
     * @param content
     * @param context
     * @return
     */
    public static boolean isSelfMMsg(String content) {
        if (content == null) {
            return false;
        }
        String tipV = BaseApplication.mInstance.getString(BaseRProxy.smschatact_upload_voice_sms_tip);
        String tipI = BaseApplication.mInstance.getString(BaseRProxy.smschatact_upload_sms_tip);
        String tipVN = tipV.replace("[", "^\\[?").replace("]", "\\]?").replace("(", "\\(").replace(")", "\\)$");
        String tipIN = tipI.replace("[", "^\\[?").replace("]", "\\]?").replace("(", "\\(").replace(")", "\\)$");
        tipVN = String.format(tipVN, ".*");
        tipIN = String.format(tipIN, ".*");
        Pattern pattern = Pattern.compile(tipVN);
        Matcher matcher = pattern.matcher(content.trim());

        Pattern pattern1 = Pattern.compile(tipIN);
        Matcher matcher1 = pattern1.matcher(content.trim());

        return matcher1.matches() || matcher.matches();
    }

    private static final int NETWORK_TYPE_UNAVAILABLE = -1;
    // private static final int NETWORK_TYPE_MOBILE = -100;
    private static final int NETWORK_TYPE_WIFI = -101;

    private static final int NETWORK_CLASS_WIFI = -101;
    private static final int NETWORK_CLASS_UNAVAILABLE = -1;
    /**
     * Unknown network class.
     */
    private static final int NETWORK_CLASS_UNKNOWN = 0;
    /**
     * Class of broadly defined "2G" networks.
     */
    private static final int NETWORK_CLASS_2_G = 1;
    /**
     * Class of broadly defined "3G" networks.
     */
    private static final int NETWORK_CLASS_3_G = 2;
    /**
     * Class of broadly defined "4G" networks.
     */
    private static final int NETWORK_CLASS_4_G = 3;

    private static DecimalFormat df = new DecimalFormat("#.##");

    // 适配低版本手机
    /**
     * Network type is unknown
     */
    public static final int NETWORK_TYPE_UNKNOWN = 0;
    /**
     * Current network is GPRS
     */
    public static final int NETWORK_TYPE_GPRS = 1;
    /**
     * Current network is EDGE
     */
    public static final int NETWORK_TYPE_EDGE = 2;
    /**
     * Current network is UMTS
     */
    public static final int NETWORK_TYPE_UMTS = 3;
    /**
     * Current network is CDMA: Either IS95A or IS95B
     */
    public static final int NETWORK_TYPE_CDMA = 4;
    /**
     * Current network is EVDO revision 0
     */
    public static final int NETWORK_TYPE_EVDO_0 = 5;
    /**
     * Current network is EVDO revision A
     */
    public static final int NETWORK_TYPE_EVDO_A = 6;
    /**
     * Current network is 1xRTT
     */
    public static final int NETWORK_TYPE_1xRTT = 7;
    /**
     * Current network is HSDPA
     */
    public static final int NETWORK_TYPE_HSDPA = 8;
    /**
     * Current network is HSUPA
     */
    public static final int NETWORK_TYPE_HSUPA = 9;
    /**
     * Current network is HSPA
     */
    public static final int NETWORK_TYPE_HSPA = 10;
    /**
     * Current network is iDen
     */
    public static final int NETWORK_TYPE_IDEN = 11;
    /**
     * Current network is EVDO revision B
     */
    public static final int NETWORK_TYPE_EVDO_B = 12;
    /**
     * Current network is LTE
     */
    public static final int NETWORK_TYPE_LTE = 13;
    /**
     * Current network is eHRPD
     */
    public static final int NETWORK_TYPE_EHRPD = 14;
    /**
     * Current network is HSPA+
     */
    public static final int NETWORK_TYPE_HSPAP = 15;

    /**
     * 获取运营商
     *
     * @return
     */
    public static String getProvider() {
        String provider = "未知";
        try {
            TelephonyManager telephonyManager = (TelephonyManager) BaseApplication.mInstance
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String IMSI = telephonyManager.getSubscriberId();
            Log.v("tag", "getProvider.IMSI:" + IMSI);
            if (IMSI == null) {
                if (TelephonyManager.SIM_STATE_READY == telephonyManager.getSimState()) {
                    String operator = telephonyManager.getSimOperator();
                    Log.v("tag", "getProvider.operator:" + operator);
                    if (operator != null) {
                        if (operator.equals("46000") || operator.equals("46002") || operator.equals("46007")) {
                            provider = "中国移动";
                        } else if (operator.equals("46001")) {
                            provider = "中国联通";
                        } else if (operator.equals("46003")) {
                            provider = "中国电信";
                        }
                    }
                }
            } else {
                if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007")) {
                    provider = "中国移动";
                } else if (IMSI.startsWith("46001")) {
                    provider = "中国联通";
                } else if (IMSI.startsWith("46003")) {
                    provider = "中国电信";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return provider;
    }

    /**
     * 获取网络类型
     *
     * @return
     */
    public static String getCurrentNetworkType() {
        int networkClass = getNetworkClass();
        String type = "未知";
        switch (networkClass) {
            case NETWORK_CLASS_UNAVAILABLE:
                type = "无";
                break;
            case NETWORK_CLASS_WIFI:
                type = "Wi-Fi";
                break;
            case NETWORK_CLASS_2_G:
                type = "2G";
                break;
            case NETWORK_CLASS_3_G:
                type = "3G";
                break;
            case NETWORK_CLASS_4_G:
                type = "4G";
                break;
            case NETWORK_CLASS_UNKNOWN:
                type = "未知";
                break;
        }
        return type;
    }

    private static int getNetworkClassByType(int networkType) {
        switch (networkType) {
            case NETWORK_TYPE_UNAVAILABLE:
                return NETWORK_CLASS_UNAVAILABLE;
            case NETWORK_TYPE_WIFI:
                return NETWORK_CLASS_WIFI;
            case NETWORK_TYPE_GPRS:
            case NETWORK_TYPE_EDGE:
            case NETWORK_TYPE_CDMA:
            case NETWORK_TYPE_1xRTT:
            case NETWORK_TYPE_IDEN:
                return NETWORK_CLASS_2_G;
            case NETWORK_TYPE_UMTS:
            case NETWORK_TYPE_EVDO_0:
            case NETWORK_TYPE_EVDO_A:
            case NETWORK_TYPE_HSDPA:
            case NETWORK_TYPE_HSUPA:
            case NETWORK_TYPE_HSPA:
            case NETWORK_TYPE_EVDO_B:
            case NETWORK_TYPE_EHRPD:
            case NETWORK_TYPE_HSPAP:
                return NETWORK_CLASS_3_G;
            case NETWORK_TYPE_LTE:
                return NETWORK_CLASS_4_G;
            default:
                return NETWORK_CLASS_UNKNOWN;
        }
    }

    private static int getNetworkClass() {
        int networkType = NETWORK_TYPE_UNKNOWN;
        try {
            final NetworkInfo network = ((ConnectivityManager) BaseApplication.mInstance
                    .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (network != null && network.isAvailable() && network.isConnected()) {
                int type = network.getType();
                if (type == ConnectivityManager.TYPE_WIFI) {
                    networkType = NETWORK_TYPE_WIFI;
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    TelephonyManager telephonyManager = (TelephonyManager) BaseApplication.mInstance
                            .getSystemService(Context.TELEPHONY_SERVICE);
                    networkType = telephonyManager.getNetworkType();
                }
            } else {
                networkType = NETWORK_TYPE_UNAVAILABLE;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return getNetworkClassByType(networkType);

    }

    // Bitmap → Drawable
    public final static Drawable convertBitmap2Drawable(Bitmap bitmap) {
        BitmapDrawable bd = new BitmapDrawable(bitmap);
        // 因为BtimapDrawable是Drawable的子类，最终直接使用bd对象即可。
        return bd;
    }

    public final static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public final static Bitmap createImage(Object data) {
        Bitmap image = null;
        try {
            if (data instanceof byte[]) {
                byte[] b = (byte[]) data;
                image = BitmapFactory.decodeByteArray(b, 0, b.length);
            } else if (data instanceof String) {
                // return Bitmap.createBitmap((String)data);
            }
        } catch (Exception e) {
            LogUtil.e("createImage error!!!");
        }
        return image;
    }
}
